from django.shortcuts import render

# Create your views here.

from django.db.models import Q
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse

from Puer.publicUtils.public_method import get_page_start_end
from models import *
from Puer.constant import constant
import json
import traceback

import datetime


# 企业团购
def company_group(request):
    try:
        name = request.GET.get("name")
        contact = request.GET.get("contact")
        region = request.GET.get("region")
        address = request.GET.get("address")
        content = request.GET.get("content")
        region = "%s/%s" % (region, address)
        now_time = datetime.datetime.now().strftime("%Y-%m-%d")
        Companygroup.objects.create(name=name,
                                    phone=contact,
                                    region=region,
                                    content=content,
                                    datetime=now_time,
                                    status=constant.UNPROCESSED)
        return HttpResponse(json.dumps("success"), content_type=constant.CONTENT_TYPE)
    except Exception as exc:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 加盟
def join_us(request):
    try:
        city = request.GET.get("city")
        name = request.GET.get("name")
        phone = request.GET.get("phone")
        content = request.GET.get("content")
        Joinus.objects.create(name=name,
                              phone=phone,
                              content=content,
                              city=city,
                              status=constant.UNPROCESSED,
                              datetime=datetime.datetime.now()
                              )
        return HttpResponse(json.dumps("success"), content_type=constant.CONTENT_TYPE)
    except Exception as exc:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# ---------------------------------------PC---------------------------------------------------------------


# 查询加盟信息
def get_joining_information(request):
    try:
        get_page = request.GET.get("page")
        get_row = request.GET.get("row")
        get_keyword = request.GET.get('keyword', None)
        get_join_us_result = Joinus.objects.all().order_by("-datetime")
        if get_keyword:
            # 模糊查询 字段 企业名称 联系人 联系电话

            get_join_us_result = Joinus.objects.filter(
                Q(city__contains=get_keyword) | Q(name__contains=get_keyword) | Q(
                    phone__contains=get_keyword)).order_by("-datetime")

        start, stop = get_page_start_end(get_page, get_row, get_join_us_result)
        data = []
        data_count = len(get_join_us_result)

        for count in range(start, stop):
            if count >= data_count:
                break

            row = {
                # 地区
                "address": ','.join(json.loads(get_join_us_result[count].city)),
                # 联系人
                "name": get_join_us_result[count].name,
                # 联系电话
                "phone": get_join_us_result[count].phone,
                # 加盟意愿
                "join_info": get_join_us_result[count].content,
                # 提交时间 时间按照格式初始化
                "time": get_join_us_result[count].datetime.strftime("%Y.%m.%d"),
                # 加盟ID
                'join_id': get_join_us_result[count].joinid,
                'status': get_join_us_result[count].status

            }
            data.append(row)
        return HttpResponse(json.dumps([data, data_count]), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


#  处理加盟信息
def deal_join(request):
    try:
        get_join_id = int(request.GET.get('joinId'))
        if not get_join_id:
            return HttpResponse(json.dumps(["failure", 'id is empty']), content_type=constant.CONTENT_TYPE)

        Joinus.objects.filter(joinid=get_join_id, status=constant.UNTREATED).update(status=constant.PROCESSED)
        return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 团购信息查询
def get_company_buy_info(request):
    try:
        get_page = request.GET.get("page")

        get_row = request.GET.get("row")
        get_keyword = request.GET.get('keyword')
        get_company_buy_result = Companygroup.objects.all().order_by("-datetime")
        start, stop = get_page_start_end(get_page, get_row, get_company_buy_result)
        data = []

        if get_keyword:
            get_company_buy_result = Companygroup.objects.filter(
                Q(company__contains=get_keyword) | Q(name__contains=get_keyword) | Q(
                    phone__contains=get_keyword)).order_by("-datetime")
        data_count = len(get_company_buy_result)
        for count in range(start, stop):
            if count >= data_count:
                break
            row = {
                # 企业名称
                "company_name": get_company_buy_result[count].company,
                # 联系人
                "name": get_company_buy_result[count].name,
                # 联系电话
                "phone": get_company_buy_result[count].phone,
                # 需求
                "content": get_company_buy_result[count].content,
                # 提交时间
                "time": get_company_buy_result[count].datetime.strftime("%Y.%m.%d"),
                # 团购ID
                "group_id": get_company_buy_result[count].groupid,
                # 状态
                "status": get_company_buy_result[count].status
            }
            data.append(row)
        return HttpResponse(json.dumps([data, data_count]), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


#  处理团购信息
def deal_group_buy(request):
    try:
        get_group_id = int(request.GET.get('groupId'))
        if not get_group_id:
            return HttpResponse(json.dumps(["failure", 'id is empty']), content_type=constant.CONTENT_TYPE)
        else:
            Companygroup.objects.filter(groupid=get_group_id, status=constant.UNTREATED).update(
                status=constant.PROCESSED)
            return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
